<template>
  <div v-loading="loading" class="track-content">
    <el-empty 
      v-if="!selectedOrder" 
      description="请先选择订单查看轨迹" 
      :image-size="80"
    >
      <el-button type="primary" size="small" @click="$emit('selectOrder')">
        选择订单
      </el-button>
    </el-empty>
    
    <el-empty 
      v-else-if="trackActivities.length === 0 && !loading" 
      description="该订单暂无轨迹信息" 
      :image-size="80"
    >
      <el-button type="primary" size="small" @click="$emit('refresh')">
        重新加载
      </el-button>
    </el-empty>
    
    <div v-else class="timeline-container">
      <!-- 详细时间线 -->
      <div class="timeline-section">
        <h3>轨迹详情</h3>
        <div class="timeline-wrapper">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in trackActivities"
              :key="index"
              :type="activity.type as 'primary' | 'success' | 'warning' | 'danger' | 'info'"
              :color="activity.color"
              :timestamp="formatTimestamp(activity.timestamp)"
              placement="top"
              :hollow="index !== 0"
              :size="index === 0 ? 'large' : 'normal'"
            >
              <el-card 
                :class="['timeline-card', { latest: index === 0 }]" 
                shadow="hover"
              >
              <div class="activity-content">
                <div class="activity-header">
                  <el-tag 
                    :type="activity.type as 'primary' | 'success' | 'warning' | 'danger' | 'info'" 
                    size="small" 
                    class="status-tag"
                    effect="dark"
                  >
                    {{ getStatusText(activity.status) }}
                  </el-tag>
                  <span class="time-ago">{{ getTimeAgo(activity.timestamp) }}</span>
                </div>
                
                <div class="activity-details">
                  <div class="location">
                    <el-icon><Location /></el-icon>
                    <span>{{ getLocationDisplay(activity) }}</span>
                    <el-tag 
                      v-if="convertingLocation.has(activity.timestamp)" 
                      size="small" 
                      type="info"
                    >
                      转换中...
                    </el-tag>
                  </div>
                  
                  <div v-if="activity.operator" class="operator">
                    <el-icon><User /></el-icon>
                    <span>操作员：{{ activity.operator }}</span>
                  </div>
                  
                  <div v-if="activity.remark" class="remark">
                    <el-icon><Document /></el-icon>
                    <span>备注：{{ activity.remark }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        </div>
      </div>
      
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect, onMounted } from 'vue'
import { Location, User, Document } from '@element-plus/icons-vue'
import { reverseGeocode, formatCoordinates } from '@/utils/geocoding'

interface TrackActivity {
  content: string
  timestamp: string
  type: string
  color: string
  location: string
  operator?: string
  remark?: string
  status: number
  coordinates?: [number, number]
}

interface Props {
  selectedOrder: string
  loading: boolean
  trackActivities: TrackActivity[]
}

interface Emits {
  (e: 'selectOrder'): void
  (e: 'refresh'): void
  (e: 'showOnMap', activity: TrackActivity): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 地址转换状态
const convertingLocation = ref(new Set<string>())
const convertedAddresses = ref(new Map<string, string>())

// 物流状态映射
const statusMap = {
  1: { text: '已下单', type: 'info', color: '#909399' },
  2: { text: '待揽件', type: 'primary', color: '#409EFF' },
  3: { text: '已揽件', type: 'primary', color: '#409EFF' },
  4: { text: '运输中', type: 'warning', color: '#E6A23C' },
  5: { text: '已到达', type: 'success', color: '#67C23A' },
  6: { text: '已签收', type: 'danger', color: '#F56C6C' },
}

// 计算属性
const currentStatus = computed(() => {
  if (props.trackActivities.length === 0) return null
  return props.trackActivities[0].status
})

const currentStatusText = computed(() => {
  if (!currentStatus.value) return '未知状态'
  return getStatusText(currentStatus.value)
})

const currentStatusType = computed(() => {
  if (!currentStatus.value) return 'info'
  return statusMap[currentStatus.value as keyof typeof statusMap]?.type || 'info'
})

// 方法
const getStatusText = (status: number): string => {
  return statusMap[status as keyof typeof statusMap]?.text || '未知状态'
}

const formatTimestamp = (timestamp: string): string => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getTimeAgo = (timestamp: string): string => {
  const now = new Date()
  const date = new Date(timestamp)
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days > 0) return `${days}天前`
  if (hours > 0) return `${hours}小时前`
  if (minutes > 0) return `${minutes}分钟前`
  return '刚刚'
}

const getTotalDuration = (): string => {
  if (props.trackActivities.length < 2) return '暂无数据'
  
  const startTime = new Date(props.trackActivities[props.trackActivities.length - 1].timestamp)
  const endTime = new Date(props.trackActivities[0].timestamp)
  const diff = endTime.getTime() - startTime.getTime()
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  
  if (days > 0) return `${days}天${hours}小时`
  return `${hours}小时`
}

const getLastUpdateTime = (): string => {
  if (props.trackActivities.length === 0) return '暂无数据'
  return getTimeAgo(props.trackActivities[0].timestamp)
}

// 获取位置显示文本
const getLocationDisplay = (activity: TrackActivity): string => {
  // 如果已经转换过地址，显示转换后的地址
  const convertedAddress = convertedAddresses.value.get(activity.timestamp)
  if (convertedAddress) {
    return convertedAddress
  }
  
  // 如果有坐标信息，显示坐标
  if (activity.coordinates) {
    const coordStr = formatCoordinates(activity.coordinates[0], activity.coordinates[1])
    return activity.location ? `${activity.location} (${coordStr})` : coordStr
  }
  
  // 否则显示原始位置信息
  return activity.location || '未知位置'
}

// 转换坐标为地址
const convertCoordinates = async (activity: TrackActivity) => {
  if (!activity.coordinates) return
  
  const [lng, lat] = activity.coordinates
  const timestamp = activity.timestamp
  
  // 如果已经转换过，跳过
  if (convertedAddresses.value.has(timestamp)) return
  
  // 添加到转换中状态
  convertingLocation.value.add(timestamp)
  
  try {
    const address = await reverseGeocode(lng, lat)
    convertedAddresses.value.set(timestamp, address)
  } catch (error) {
    console.error('地址转换失败:', error)
    // 如果转换失败，使用格式化的坐标作为备选
    const fallbackAddress = `位置: ${formatCoordinates(lng, lat)}`
    convertedAddresses.value.set(timestamp, fallbackAddress)
  } finally {
    // 移除转换中状态
    convertingLocation.value.delete(timestamp)
  }
}

// 自动转换所有轨迹点的坐标
const autoConvertAllCoordinates = async () => {
  const activitiesWithCoordinates = props.trackActivities.filter(activity => activity.coordinates)
  
  if (activitiesWithCoordinates.length === 0) return
  
  console.log(`🗺️ 开始自动转换 ${activitiesWithCoordinates.length} 个轨迹点的坐标...`)
  
  // 批量转换，但限制并发数量
  const batchSize = 3
  for (let i = 0; i < activitiesWithCoordinates.length; i += batchSize) {
    const batch = activitiesWithCoordinates.slice(i, i + batchSize)
    const promises = batch.map(activity => convertCoordinates(activity))
    await Promise.all(promises)
    
    // 添加小延迟，避免过于频繁的转换
    if (i + batchSize < activitiesWithCoordinates.length) {
      await new Promise(resolve => setTimeout(resolve, 100))
    }
  }
  
  console.log('✅ 所有轨迹点坐标转换完成')
}

// 监听轨迹数据变化，自动转换坐标
watchEffect(() => {
  if (props.trackActivities.length > 0) {
    autoConvertAllCoordinates()
  }
})
</script>

<style scoped>
.track-content {
  height: 100%;
  overflow-y: auto;
  padding: 0 20px;
  position: relative;
}

.status-overview {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 32px;
  border: 1px solid #e2e8f0;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
  font-weight: 600;
}

.timeline-section {
  margin-bottom: 32px;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.timeline-section h3 {
  margin: 0 0 24px 0;
  color: #1e293b;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 2px solid #e2e8f0;
  flex-shrink: 0;
}

.timeline-wrapper {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px;
  min-height: 0;
}

.timeline-container {
  padding: 0;
  height: 100%;
  overflow-y: visible;
}

.timeline-card {
  margin-bottom: 16px;
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid #e2e8f0;
}

.timeline-card.latest {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.timeline-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.activity-content {
  padding: 20px;
}

.activity-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.status-tag {
  flex-shrink: 0;
  font-weight: 500;
}

.activity-content h4 {
  margin: 0;
  color: #1e293b;
  font-size: 15px;
  font-weight: 600;
  flex: 1;
}

.time-ago {
  font-size: 12px;
  color: #64748b;
  flex-shrink: 0;
}

.activity-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.location, .operator, .remark {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  padding: 8px 0;
}

.location {
  color: #3b82f6;
}

.operator {
  color: #10b981;
}

.remark {
  color: #64748b;
  font-style: italic;
}

.statistics {
  margin-top: 32px;
}

.stats-card {
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  text-align: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-label {
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
}

.stat-value {
  font-size: 18px;
  color: #1e293b;
  font-weight: 600;
}

.track-content::-webkit-scrollbar {
  width: 8px;
}

.track-content::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

.track-content::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
  transition: background 0.2s;
}

.track-content::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.timeline-wrapper::-webkit-scrollbar {
  width: 6px;
}

.timeline-wrapper::-webkit-scrollbar-track {
  background: #f8fafc;
  border-radius: 3px;
}

.timeline-wrapper::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
  transition: background 0.2s;
}

.timeline-wrapper::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

@media (max-width: 768px) {
  .track-content {
    padding: 0 16px;
    height: 100%;
    overflow-y: auto;
  }
  
  .status-overview {
    padding: 20px;
    margin-bottom: 24px;
  }
  
  .status-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .activity-header {
    flex-wrap: wrap;
  }
  
  .activity-details .location {
    flex-wrap: wrap;
  }
  
  .stats-content {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .timeline-section h3 {
    margin-bottom: 16px;
  }
  
  .timeline-container {
    overflow-y: visible;
  }
}
</style>